package com.healthcloud.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.healthcloud.dao.PatientMapper;
import com.healthcloud.dao.PhysicalExamMapper;
import com.healthcloud.entity.Condition;
import com.healthcloud.entity.Patient;
import com.healthcloud.entity.PatientCriteria;
import com.healthcloud.entity.PhysicalExam;
import com.healthcloud.entity.UserFamily;
import com.healthcloud.query.CriteriaUtils;
import com.healthcloud.service.PatientService;
import com.healthcloud.service.UserFamilyService;
import com.healthcloud.utils.DateUtils;
import com.healthcloud.utils.Pagine;
import com.healthcloud.vo.PatientVo;

/**
 * Created by xiam on 2015/6/17.
 */
@Service
@Transactional
public class PatientServiceImpl implements PatientService {

	@Autowired
	private PatientMapper patientMapper;
	@Autowired
	private PhysicalExamMapper physicalExamMapper;
	@Autowired
	private UserFamilyService userFamilyService;

	@Transactional
	@Override
	public Patient saveOrUpdate(Patient patient) {
		if (!patient.getBirthdayOfString().isEmpty()) {
			patient.setBirthday(patient.StringFormatDate("yyyy-MM-dd", patient.getBirthdayOfString()));
		}
		patient.setIdCard((patient.getIdCard() != null && patient.getIdCard().equals("")) ? null : patient.getIdCard());//设置idCard不能为空字符串，可为null
		Patient old = null;
		// 先从数据库中查找是否已经有病人信息
		if (patient.getId() != null) {
			old = patientMapper.get(patient.getId());
		} else if (StringUtils.isNotBlank(patient.getIdCard())) {
			old = patientMapper.findByIdCard(patient.getIdCard());
		}
		if (old != null) { // 更新
			patient.setId(old.getId());
			patient.setUpdatedTime(new Date());
			patient.setCreatedTime(old.getCreatedTime());
			if (old.getUserId() != null) {
				patient.setUserId(old.getUserId());
			}
			patientMapper.update(patient);
			return patient;
		}
		//新增
		patient.setUpdatedTime(new Date());
		patient.setCreatedTime(new Date());
		patientMapper.save(patient);
		return patient;
	}

	@Override
	public Patient findByIdCard(String idCard) {
		Patient p = patientMapper.findByIdCard(idCard);
		if (p != null && p.getBirthday() != null) {
			try {
				p.setAge(DateUtils.getAge(p.getBirthday()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return patientMapper.findByIdCard(idCard);
	}

	@Override
	public Page<Patient> search(PatientCriteria criteria, Pageable pageable) {
		List<Condition<Object>> conditions = CriteriaUtils.getConditions(criteria);
		Pagine<Patient> pagine = new Pagine<>(pageable);
		patientMapper.criteriaSearch(conditions, pagine);
		return pagine;
	}

	//获取跟医生关联的病人列表
	public List findByExam(String docId) {
		List<PatientVo> pvList = new ArrayList();
		String sqlWhere = " 1=1";
		if (docId == "all" || docId.equals("all")) {//医生编号为all则获取所有病人列表
			List<Patient> patients = patientMapper.findByEntity(null, null);
			if (patients != null && patients.size() > 0) {
				for (Patient pt : patients) {
					PatientVo pv = new PatientVo();
					pv.setIdCard(pt.getIdCard());
					pv.setRealName(pt.getRealname());
					pvList.add(pv);
				}
			}
			return pvList;
		} else {
			if (StringUtils.isNotBlank(docId)) {//医生编号为空则获取所有有体检信息的病人
				sqlWhere += " physicalexamination.doctorId=" + docId;
			}
			sqlWhere += " GROUP BY idcard ORDER BY examDate";
			List<PhysicalExam> li = physicalExamMapper.customCondition(sqlWhere);
			if (li != null && li.size() > 0) {
				for (PhysicalExam pe : li) {
					PatientVo pv = new PatientVo();
					pv.setIdCard(pe.getIdCard());
					pv.setDoctorId(docId);
					Date dt = pe.getExamDate();
					if (dt != null) {
						String dStr = DateUtils.format(DateUtils.Date2Calendar(dt), "yyyy-MM-dd HH:mm:ss");
						pv.setLastExamDate(dStr);
					}
					Patient pt = findByIdCard(pv.getIdCard());
					if (pt != null) {
						pv.setRealName(pt.getRealname());
					}
					pvList.add(pv);
				}
			}
			return pvList;
		}
	}

	@Override
	public boolean existsPatient(String idCard, String socialInsuranceNum) {
		//boolean ex = false;
		return true;
	}

	/*
	 * 数据回传是需要进行Date数据处理
	 */
	public void DataTimeToString(Patient patient) {
		if (patient.getBirthday() != null) {
//			patient.setBirthdayOfString(patient.DateTimeTransformString(patient.getBirthday()));
			patient.setBirthdayOfString(patient.DateChangeString("yyyy-MM-dd", patient.getBirthday()));
			patient.setBirthday(null);
		}
		if (patient.getCreatedTime() != null) {
			patient.setCreatedTimeOfString(patient.DateTimeTransformString(patient.getCreatedTime()));
			patient.setCreatedTime(null);
		}
		if (patient.getUpdatedTime() != null) {
			patient.setUpdatedTimeOfString(patient.DateTimeTransformString(patient.getUpdatedTime()));
			patient.setUpdatedTime(null);
		}
	}

	@Override
	public Patient findByUserId(Integer userId) {
		return patientMapper.findByUserId(userId);
	}

	@Override
	public List<Patient> getFamilyPatientList(Long userId) {
		List<Patient> patientList = new ArrayList<>();
		List<UserFamily> userFamilyList = userFamilyService.getByUserId(userId);
		List<Long> idList = new ArrayList<>();
		for (UserFamily userFamily : userFamilyList) {
			idList.add(userFamily.getPatientId());
		}
		try {
			patientList = this.getByIds(idList.toArray(new Long[idList.size()]));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return patientList;
	}

	@Override
	public Patient getById(Long id) {
		return patientMapper.get(id);
	}

	@Override
	public List<Patient> getByIds(Long[] ids) throws IllegalArgumentException {
		if (ids.length == 0) {
			return new ArrayList<>();
		} else {
			for (int i = 0; i < ids.length; i++) {
				if (ids[i] == null) {
					throw new IllegalArgumentException();
				}
			}
		}
		return patientMapper.getByIds(ids);
	}
}
